
cd $directory

************************************************
*Set list of margins; becomes points on x axis
************************************************

global MARGLIST = "50 75 100 150 225 330 500 750 1000 1500 2250 3300 5000 7500 10000 15000 22500 33000 50000 75000 100000"
global MARGLISTPCT = ".0000001 .0000002 .0000005 .000001 .000002 .000005 .00001 .00002 .00005 .0001 .0002 .0005 .001"



global LIST = "52201"


************************************************
*Storage for Summary Statistics
************************************************

matrix define REC		=J(30, 10, .) 		//table of summary of reversal rates; 						columns are models, rows are critical margins of votes dropped from winner or gained by loser
matrix define RECPCT	=J(30, 10, .) 		//table of summary of reversal rates based on % margins; 	columns are models, rows are %critical margins of votes dropped from winner or gained by loser
matrix define RECDECWIN	=J(30, 10, .) 		//table of summary of reversal rates; condl on D EC WINS
matrix define RECRECWIN	=J(30, 10, .) 		//table of summary of reversal rates; condl on R EC WINS
matrix define RECRECFRACWIN	=J(30, 10, .) 		//table of summary of reversal rates; condl frac of R EC WINS
matrix define RPV		=J(30, 10, .) 		//table of summary of NPV reversal rates;
matrix define RPVPCT	=J(30, 10, .) 		//table of summary of NPV reversal rates; in % margins (pp)

************************************************
*Outer loop - open datasets
************************************************

global LOOP = 2

foreach file in $LIST{

	use "source_data`c(dirsep)'`file'.dta", clear

************************************************
*stats and vars
************************************************

//count states 
local error=0
local counter=1
while `error' != 111 {
	qui cap d total_ev_`counter'
	local error=_rc
	local counter=`counter'+1
}
global STATECOUNT = `counter'-2 
di "$STATECOUNT"
local state_count = `counter'-2 


	//make vars that summarize each election
	qui egen pvotes = rowtotal(twoPartyVotes_*)
	forvalues i = 1(1)`state_count'{
		qui gen rvotes_`i' = twoPartyVotes_`i'* R_pvShare_`i'
	}
	qui egen rvotes = rowtotal(rvotes_*)
	qui gen pvshare = rvotes/pvotes
	qui gen margin_share = abs(0.5-pvshare)*2
	qui gen margin_votes = margin_share*pvotes

	forvalues i = 1(1)`state_count'{
		qui gen rwin_`i' = R_pvShare_`i' > .5
		qui gen rev_`i' = rwin_`i' * total_ev_`i'
	}
	qui egen revn_total= rowtotal(rev_*)
	qui egen ev_denominator = rowtotal(total_ev_*)
	qui gen rwin = revn_total/ev_denominator > 0.5
	qui gen dwin = (ev_denominator-revn_total)/ev_denominator > 0.5
	qui gen cf_revn_total  = revn_total
	qui gen cf_rwin = rwin

	qui gen inv=0
	qui replace inv=1 if  (rwin==1 & pvshare<.5) | (rwin==0 & pvshare>.5)
	
	//This loop identifies which states can flip election on their own (swing==1) and if so, 
	//how many votes must be dropped to do it(vmargin==X)
	forvalues i = 1(1)`state_count'{
		qui gen vmargin_`i' =  twoPartyVotes_`i'*abs(0.5- R_pvShare_`i')*2 //multiply by 2 to get the number of votes that separate candidates ((1-Rshare)-Rshare) = 1-2rshare
		qui replace cf_revn_total = revn_total //reset each loop
		qui replace cf_rwin = rwin //reset each loop
		qui replace cf_revn_total = cf_revn_total - total_ev_`i' if rwin_`i' == 1 //substract state to ECV count if R won the sim (nationally)
		qui replace cf_revn_total = cf_revn_total + total_ev_`i' if rwin_`i' == 0 //add state from ECV count if R lost the sim (nationally)
		qui replace cf_rwin =  cf_revn_total/ev_denominator > 0.5 //did R win in the counterfactual flip of the state?
		qui gen swing_`i' = cf_rwin != rwin //did the outcome of the election change? 
		//^this allows a change from not a tie to a tie or vice versa to count as a change
		qui replace vmargin_`i' = . if swing_`i' == 0 //keep vmargin blank if the state can't flip the election alone
		label var vmargin_`i' "The margin in vote counts in state `i', if `i' could flip EC"
		
		//Levels: cylce through marglist to get probability of flips at each margin
		foreach marg in $MARGLIST{
			qui gen swing`marg'_`i' = swing_`i'==1 & vmargin_`i'<`marg'
			label var swing`marg'_`i' "Binary: is vmargin_`i' less than `marg'"
		}
		//PP: cylce through % marglist to get probability of flips at each margin
		foreach marg in $MARGLISTPCT{
			local labelmarg = round(1/`marg')  //cant have decimals in localvars used as names
			qui gen swingpct`labelmarg'_`i' = swing_`i'==1 & (vmargin_`i'/pvote)<`marg'
			label var swingpct`labelmarg'_`i' "Binary: is vmargin_`i' less than `marg' expressed as pct of turnout"
		}	
		
	}
	
	qui gen closest_flippable_state=.
	qui egen min_vmargin = rowmin(vmargin_*) 
	label var min_vmargin "minimum votes needed to flip closest state"
	qui gen tipping_state = .
	forvalues i = 1(1)`state_count'{
		qui replace closest_flippable_state = `i' if min_vmargin == vmargin_`i'
	}
	egen swingers = rowtotal(swing_*)
	
	//Levels EC Reversals 
	foreach marg in $MARGLIST{
		qui egen swing`marg' = rowtotal(swing`marg'_*)
		qui replace swing`marg' = 0 if swing`marg' == .
		*qui gen notReversed`marg' = swing`marg'==0
		*label var notReversed`marg' "EC not reversed by one state dropping `marg' votes"
		qui gen Reversed`marg' = (swing`marg'>0 & swing`marg'<51)
		qui replace Reversed`marg' = 0 if swing`marg' == .
		label var Reversed`marg' "EC reversed by at least one state dropping `marg' votes"
	}
		
	//PP EC Reversals
	foreach marg in $MARGLISTPCT{
		local labelmarg = round(1/`marg')  //cant have decimals in localvars used as names
		di `labelmarg'
		qui egen swingpct`labelmarg' = rowtotal(swingpct`labelmarg'_*)
		qui replace swingpct`labelmarg' = 0 if swingpct`labelmarg' == .
		*qui gen notReversed`marg' = swing`marg'==0
		*label var notReversed`marg' "EC not reversed by one state dropping `marg' votes"
		qui gen Reversedpct`labelmarg' = (swingpct`labelmarg'>0 & swingpct`labelmarg'<51)
		qui replace Reversedpct`labelmarg' = 0 if swingpct`labelmarg' == .
		label var Reversedpct`labelmarg' "EC reversed by at least one state dropping `marg' pp votes"
	}
	
	//Levels NPV Reversals
	foreach marg in $MARGLIST{
		qui gen PVswing`marg'=0
		qui replace PVswing`marg' = 1 if margin_votes<`marg'
	}
	//PP NPV Reversals
	foreach marg in $MARGLISTPCT{
		local labelmarg = round(1/`marg')  //cant have decimals in localvars used as names
		qui gen PVswingpct`labelmarg'=0
		qui replace PVswingpct`labelmarg' = 1 if (margin_votes/pvotes)<`marg'
	}	

	qui replace swingers = 0 if swingers == .
	qui gen ec_margin = min_vmargin
	qui gen pv_margin = margin_votes
	
	qui gen zero = swingers == 0
	label var swingers "number of states that could swing election"
		
	************************************************
	*Data for  figures
	************************************************
	local col = $LOOP
	di `col'
	di `file'
	matrix REC[1, `col'] 		= `file'
	matrix RECPCT[1, `col'] 	= `file'
	matrix RECDECWIN[1, `col'] 	= `file'
	matrix RECRECWIN[1, `col'] 	= `file'
	matrix RECRECFRACWIN[1, `col'] 	= `file'	
	matrix RPV[1, `col'] 		= `file'
	matrix RPVPCT[1, `col']		= `file'	

	local row = 2 //place marglist in rows starting at 2
	//stores fraction of sims reversed by indicated margin
	foreach marg in $MARGLIST{

		matrix REC[`row',1] = `marg'
		matrix RECDECWIN[`row',1] = `marg'
		matrix RECRECWIN[`row',1] = `marg'
		matrix RECRECFRACWIN[`row',1] = `marg'
		matrix RPV[`row',1] = `marg'
		
		qui summ Reversed`marg'
		matrix REC[`row',`col'] = r(mean)
		
		qui summ Reversed`marg' if dwin==1
		matrix RECDECWIN[`row',`col'] = r(mean)
		qui count if Reversed`marg'==1 & dwin==1	
		local decwin = r(N)
		
		qui summ Reversed`marg' if rwin==1
		matrix RECRECWIN[`row',`col'] = r(mean)
		qui count if Reversed`marg'==1 & rwin==1
		local recwin = r(N)
		
		matrix RECRECFRACWIN[`row',`col']=`recwin'/(`recwin'+`decwin')
		
		qui summ PVswing`marg'
		matrix RPV[`row',`col'] = r(mean)		
		
		local row = `row'+1
	}
	
	local row = 2 //place marglist in rows starting at 2
	//stores fraction of sims reversed by indicated margin
	foreach marg in $MARGLISTPCT{
		local labelmarg = round(1/`marg')  //cant have decimals in localvars used as names
		matrix RECPCT[`row',1] = `marg'
		matrix RPVPCT[`row',1] = `marg'
		
		qui summ Reversedpct`labelmarg'
		matrix RECPCT[`row',`col'] = r(mean)
		qui summ PVswingpct`labelmarg'
		matrix RPVPCT[`row',`col'] = r(mean)		
		
		local row = `row'+1
	}	
	
	
	************************************************
	*Match Moments
	************************************************
	//match moments
	
	/* Notes
	
	z = invnormal(p) returns the z score X that generates the probability p: Pr(z<X)=p, 
	so invnormal(-.025) returns -1.96
	
	
	Generate statistics to match:
	
	//find corresponding sigmas
	//Int^{z/2}_{z/2}(Phi) = Int^{m/sigma*2}_{m/sigma*2}(Phi) = p
	//test function is single sided, so divide p by 2 and subtract from .5. Example for p
	//sigma of interest is margin (in pp) divided by the z returned
	//Z = marg/(2*sigma) (both m and sigma in pp terms), sigma = marg/(2*Z)
	*/
	
	
	
	//Make vote shares Normal
	cap drop marginMatch
	cap drop pMatch
	gen marginMatch = .
	
	gen pMatch = .
	
	local i = 1
	foreach marg in $MARGLISTPCT{
		local labelmarg = round(1/`marg')
	
		replace marginMatch = `marg'*100 in `i' //marg in pp (so (votes/turnout) * 100)
		
		summ Reversedpct`labelmarg'
		replace pMatch = r(mean) in `i'
		local i = `i' + 1
	}
	
	cap drop sigmaMatch
	gen sigmaMatch = -marginMatch/(2*invnormal(0.5 - (pMatch/2)))
	
	gen marginMatchTurnout = 150000000*marginMatch/100 //margin match are in points
	mkmat marginMatch marginMatchTurnout pMatch sigmaMatch in 1/15, matrix(MATCH)
	
	xml_tab MATCH, save("tables`c(dirsep)'TableA2") replace
	

************************************************
*Outer loop - open datasets
************************************************
	
global LOOP = $LOOP +1		
di "$LOOP"
	
}
